<?php
/*
	TrixBi v0.01
	small billing for Trixbox
	GNU GPL v2
*/
require_once("mySQL.php");
class Auth extends mySQL{
	public function CodeGen( $length=6 ){
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
		$code = "";
		$StrLen = strlen($chars) - 1;
		while( strlen($code) < $length ){
			$code .= $chars[mt_rand(0,$StrLen)];
		}
		return $code;
	}
	public function AuthGet( $login, $passwd ){
		$this->login = $login;
		$this->passwd = $passwd;
		$this->myQ = parent::myQuery("SELECT * FROM users WHERE `user_login`='".$this->login."'LIMIT 1", 
										"trixbi",
										TRUE);
		if($this->myQ)
		foreach($this->myQ as $this->myQ){
			if($this->myQ['user_password'] === md5(md5($this->passwd))){
				$this->hash = md5(md5($this->CodeGen()));
				parent::myQuery("update users set `user_hash`='".$this->hash."' where `user_id`='".$this->myQ['user_id']."'", 
								"trixbi");
				setcookie("uid", $this->myQ['user_id'], 0, "/");
				setcookie("hash", $this->hash, 0, "/");
				header("Location: index.php");
			}
		}
	}
	public function logout(){
		$this->myQuery("UPDATE users SET `user_hash`='NULL' WHERE `user_hash`='".$_COOKIE['hash']."'", "trixbi");
		header("Location: index.php");
	}
	public function ShForm(){
		echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link href="styles/main.css" type="text/css" rel="stylesheet" />
		<title>Asterisk billing module</title>
		</head>
		<body>
		 <form method="post">
		  <table id="t_border" width="300" align="center">
		    <tr>
		     <td>Логин: </td>
		     <td><input type="text" checked="true" name="login" /></td>
		    </tr>
		    <tr>
		     <td>Пароль: </td>
		     <td><input type="password" name="password" /></td>
		    </tr>
		    <tr><td><input type="submit" name="submit" value="OK" /></td></tr>
		  </table> 
		 </form>
		</body>
		</html>';
		die();
	}
	public function isAuth(){
			$Cookie = parent::myQuery("SELECT * FROM users WHERE user_id = '".intval($_COOKIE['uid'])."' LIMIT 1", 
						"trixbi",
						TRUE);
			if($Cookie) 
				foreach($Cookie as $Cookie){
					if(($Cookie['user_hash'] !== $_COOKIE['hash']) 
						or ($Cookie['user_id'] !== $_COOKIE['uid']) 
						or ($Cookie['user_hash'] === '0')
						or (!isset($_COOKIE['uid']))
						or (!isset($_COOKIE['hash']))){
							return FALSE;
					}
					else
						return TRUE;
				}
	}
}
?>
